package com.campus.merchant.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.common.bean.common.PageUtil;

import com.campus.merchant.entity.Notice;
import com.campus.merchant.mapper.NoticeMapper;
import com.campus.merchant.vo.notice.NoticeListVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 公告表 服务实现类
 * </p>
 *
 * @author ZhaoYuJie
 * @since 2025-07-15
 */
@Service
public class NoticeService extends ServiceImpl<NoticeMapper, Notice> {

    private List<NoticeListVO> convertToNoticeListVOList(List<Notice> notices) {
        List<NoticeListVO> voList = new ArrayList<>();
        for (Notice notice : notices) {
            NoticeListVO vo = new NoticeListVO();
            BeanUtil.copyProperties(notice, vo);
            voList.add(vo);
        }
        return voList;
    }
    
    public List<NoticeListVO> getNoticeList() {
        // 直接获取所有公告列表，不分页
        List<Notice> notices = getNoticeData();
        return convertToNoticeListVOList(notices);
    }

    public PageInfo<NoticeListVO> getNoticeListPage(Integer pageNo, Integer pageSize) {
        // 使用正确的分页参数获取公告列表
        PageInfo<Notice> pageInfo = PageHelper.startPage(pageNo, pageSize)
                .doSelectPageInfo(() -> getNoticeData());
        List<NoticeListVO> noticeVOList = convertToNoticeListVOList(pageInfo.getList());

        return PageUtil.convertPageInfo(pageInfo, noticeVOList);
    }

    private List<Notice> getNoticeData() {
        LocalDateTime now = LocalDateTime.now();
        List<Notice> notices = baseMapper.selectList(Wrappers.<Notice>lambdaQuery()
                .eq(Notice::getStatus, 1) // 固定查询启用状态的公告
                .and(wrapper -> wrapper.eq(Notice::getTargetType, 0).or().eq(Notice::getTargetType, 2)) // 全部端或商户端
                .le(Notice::getStartTime, now)
                .ge(Notice::getEndTime, now)
                .orderByDesc(Notice::getIsTop)
                .orderByDesc(Notice::getPriority)
                .orderByDesc(Notice::getCreateTime));
        
        return notices;
    }

}
